package com.gem.controller;

import com.alibaba.druid.util.StringUtils;
import com.gem.domain.Teacher;
import com.gem.service.TeacherService;
import com.gem.util.ExcelUtil;
import com.gem.util.JSONResultUtil;
import com.gem.util.MessageUtil;
import com.gem.util.PageUtil;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Bravea❤ ·勇
 * Description: 授课人信息controller
 * create
 * Modified By:
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private JSONResultUtil result;

    @Autowired
    private TeacherService teacherService;

    @RequestMapping("/list")
    public String list(Model model,
                            @RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                            @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        PageInfo<Teacher> pageBean = teacherService.selectTeacherByPage(currentPage,pageSize);
        if (currentPage > pageBean.getPages()){
            currentPage = pageBean.getPages();
            pageBean = teacherService.selectTeacherByPage(currentPage,pageSize);
        }
        model.addAttribute("pageBean", pageBean);
        if(pageBean != null && pageBean.getList().size() > 0){
            List<Integer> pageValue = PageUtil.getPageValue(pageBean.getPages(),currentPage);
            model.addAttribute("pageValue",pageValue);
        }else {
            model.addAttribute("info","没有授课人信息，请先添加！");
        }
        return "company/teacher";
    }

    @RequestMapping("/modifyUI")
    public String modifyUI(String tId,Model model,String searchUrl,
                                @RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                                @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        if(tId == null || tId.trim().equals("")){
            if (searchUrl == null){
                MessageUtil.returnInfoPage("3","/teacher/list?currentPage="+currentPage+"&pageSize="+pageSize,"传递参数为空",model);
            }else {
                MessageUtil.returnInfoPage("3",searchUrl+"&currentPage="+currentPage+"&pageSize="+pageSize,"传递参数为空",model);
            }
            return "message";
        }
        Teacher teacher = teacherService.selectTeacherById(tId);
        if (teacher == null){
            if (searchUrl == null) {
                MessageUtil.returnInfoPage("3","/teacher/list?currentPage="+currentPage+"&pageSize="+pageSize,"没有该授课人信息",model);
            }else {
                MessageUtil.returnInfoPage("3",searchUrl+"&currentPage="+currentPage+"&pageSize="+pageSize,"没有该授课人信息",model);
            }
            return "message";
        }
        model.addAttribute("searchUrl",searchUrl);
        model.addAttribute("currentPage",currentPage);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("teacher",teacher);
        return "company/teacher_update";
    }

    @RequestMapping("/modify")
    public String modify(Teacher teacher,Model model,String searchUrl,
                              @RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                              @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        boolean isModifySuccess = teacherService.modifyTeacherById(teacher);
        if(isModifySuccess){
            if(searchUrl != null && !searchUrl.trim().equals("")){
                MessageUtil.returnInfoPage("3",searchUrl+"&currentPage="+currentPage+"&pageSize="+pageSize,"修改成功！",model);
            }else {
                MessageUtil.returnInfoPage("3", "/teacher/list?currentPage=" + currentPage + "&pageSize=" + pageSize, "修改成功！", model);
            }
        }else {
            if(searchUrl != null && !searchUrl.trim().equals("")){
                MessageUtil.returnInfoPage("3",searchUrl+"&currentPage="+currentPage+"&pageSize="+pageSize,"修改未成功，请检查！",model);
            }else {
                MessageUtil.returnInfoPage("3", "/teacher/list?currentPage=" + currentPage + "&pageSize=" + pageSize, "修改未成功，请检查！", model);
            }
        }
        return "message";
    }

    @RequestMapping("/addUI")
    public String addUI(@RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,String searchUrl,
                             @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,Model model){
        model.addAttribute("currentPage",currentPage);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("searchUrl",searchUrl);
        return "company/teacher_insert";
    }

    @RequestMapping("/add")
    public String add(Teacher teacher,Model model,String searchUrl,
                           @RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                           @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        boolean isAddSuccess = teacherService.addTeacher(teacher);
        if(isAddSuccess){
            if(searchUrl != null && !searchUrl.trim().equals("")){
                MessageUtil.returnInfoPage("3",searchUrl+"&currentPage="+currentPage+"&pageSize="+pageSize,"添加成功！",model);
            }else {
                MessageUtil.returnInfoPage("3","/teacher/list?currentPage="+currentPage+"&pageSize="+pageSize,"添加成功！",model);
            }
        }else {
            if(searchUrl != null && !searchUrl.trim().equals("")){
                MessageUtil.returnInfoPage("3",searchUrl+"&currentPage="+currentPage+"&pageSize="+pageSize,"添加失败，请检查！",model);
            }else {
                MessageUtil.returnInfoPage("3","/teacher/list?currentPage="+currentPage+"&pageSize="+pageSize,"添加失败，请检查！",model);
            }
        }
        return "message";
    }

    @RequestMapping("/search")
    public String search(Model model,Teacher teacher,
                              @RequestParam(value = "currentPage",defaultValue = "1") Integer currentPage,
                              @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        if (teacher.getTName() == null){
            teacher.setTName("");
        }
        if (teacher.getTMajor() == null){
            teacher.setTMajor("");
        }
        PageInfo<Teacher> pageBean = teacherService.searchTeacherByPage(currentPage,pageSize,teacher.getTName(),teacher.getTMajor());
        if (currentPage > pageBean.getPages()){
            currentPage = pageBean.getPages();
            pageBean = teacherService.searchTeacherByPage(currentPage,pageSize,teacher.getTName(),teacher.getTMajor());
        }
        if(pageBean != null && pageBean.getList().size() > 0 && pageBean.getPages() > 0 && pageBean.getTotal() > 0){
            List<Integer> pageValue = PageUtil.getPageValue(pageBean.getPages(),currentPage);
            model.addAttribute("pageValue",pageValue);
        }else {
            model.addAttribute("info","没有授课人信息，请先添加！");
        }
        model.addAttribute("pageBean",pageBean);
        model.addAttribute("tName",teacher.getTName());
        model.addAttribute("tMajor",teacher.getTMajor());
        model.addAttribute("searchUrl","/teacher/search?tName="+teacher.getTName()+"&tMajor="+teacher.getTMajor());
        return "company/teacher";
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    @ResponseBody
    public JSONResultUtil delete(String[] checks){
        try {
            if (checks != null && checks.length>0) {
                if (teacherService.deleteTeacherById(checks)) {
                    result.setId(0);
                    result.setData("删除成功！");
                } else {
                    result.setId(-1);
                    result.setData("删除失败！");
                }
            } else {
                result.setId(-1);
                result.setData("没有提交编号参数哦！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setId(-1);
            result.setData("服务器异常，请联系管理员哦！");
        }
        return result;
    }

    /**
     * 以下是POI部分
     */
    //导出excel模板
    @RequestMapping("/exportTemplate")
    public void exportExcelTemplate(HttpServletResponse response, HttpSession session){
        try {
            //创建excel工作簿对象//一个表格文件！
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建sheet对象//一个表单！
            HSSFSheet sheet = workbook.createSheet("Sheet1");

            //创建水平垂直居中的cellStyle单元格样式对象
            HSSFCellStyle cellStyle = ExcelUtil.getTitleStyle(workbook);

            //创建水平垂直居中加粗的cellStyle单元格样式,给表头试用
            HSSFCellStyle cellStyle2 = ExcelUtil.getThStyle(workbook);

            //模板第一行例子展示
            HSSFCellStyle cellStyle3 = ExcelUtil.getExamplStyle(workbook);

            // 单元格类型日期格式化
            HSSFCellStyle cellStyleDate = ExcelUtil.getDateRedStyle(workbook);

            //创建行对象
            HSSFRow row = null;

            // 将第一行的三个单元格给合并,模板固定
            //注意 java的参数是从0开始 即表示excel中的一行或者第一列  //Row行 Col列
            sheet = getRows(sheet, cellStyle, cellStyle2);
            //在第四行给一行数据模板,根据对应表的对应字段填写
            row = sheet.createRow(3);
            row.createCell(0).setCellValue("张三");
            //第二列 电话
            row.createCell(1).setCellValue("15797927591");
            //第三列 QQ
            row.createCell(2).setCellValue("1747395347");
            //第四列 微信
            row.createCell(3).setCellValue("15727774219");
            //第五列 邮箱
            row.createCell(4).setCellValue("1743471@qq.com");
            //第六列 授课人擅长内容
            row.createCell(5).setCellValue("java");
            //第七列 课酬
            row.createCell(6, CellType.NUMERIC).setCellValue(20000);
            //第九列 常住地
            row.createCell(7).setCellValue("文萃人才公寓");
            //备注
            row.createCell(8).setCellValue("备注可写可不写");

            for (int i = 0; i < 9; i++) {
                row.getCell(i).setCellStyle(cellStyle3);

            }

            OutputStream outputStream = response.getOutputStream();
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=teacher.xls");

            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //导出excel
    @RequestMapping("/export")
    public void exportExcel(HttpServletResponse response) {
        try {
            //创建excel工作簿对象
            HSSFWorkbook workbook = new HSSFWorkbook();
            //创建sheet对象
            HSSFSheet sheet = workbook.createSheet("Sheet1");

            //创建水平垂直居中的cellStyle单元格样式对象
            HSSFCellStyle cellStyle = ExcelUtil.getTitleStyle(workbook);

            //创建水平垂直居中加粗的cellStyle单元格样式,给表头试用
            HSSFCellStyle cellStyle2 = ExcelUtil.getThStyle(workbook);

            //居中
            HSSFCellStyle cellStyle3 = ExcelUtil.getCenterStyle(workbook);

            // 单元格类型日期格式化
            HSSFCellStyle cellStyleDate = ExcelUtil.getDateStyle(workbook);

            //创建行对象
            HSSFRow row = null;
            sheet = getRows(sheet, cellStyle, cellStyle2);

            //调用service方法查询所有数据集合
            List<Teacher> teachers = teacherService.selectAllTeacher();

            Teacher t = null;

            for (int i = 0; i < teachers.size(); i++) {
                row = sheet.createRow(i + 3);
                t = teachers.get(i);
                //第一列,姓名
                row.createCell(0).setCellValue(t.getTName());
                //优化 降低冗余
                HSSFCell cell = null;//主要用于表格里时间的格式化
                //第二列 电话
                row.createCell(1).setCellValue(t.getTPhone());
                //第三列 QQ
                row.createCell(2).setCellValue(t.getTQq());
                //第四列 微信
                row.createCell(3).setCellValue(t.getTWechat());
                //第五列 邮箱
                row.createCell(4).setCellValue(t.getTEmail());
                //第六列 授课人擅长信息
                row.createCell(5).setCellValue(t.getTMajor());
                //第七列 课酬
                row.createCell(6).setCellValue(t.getTMoney());
                //第八列 常住地
                row.createCell(7).setCellValue(t.getTAddress());
                //第九列 备注
                row.createCell(8).setCellValue(t.getTRemarks());
                //设置垂直水平居中
                for (int j = 0; j < 9; j++) {
                    row.getCell(j).setCellStyle(cellStyle3);
                }
            }

            OutputStream outputStream = response.getOutputStream();
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=teacher.xls");

            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //导出模板和导出数据抽出的共同方法
    private HSSFSheet getRows(HSSFSheet sheet, HSSFCellStyle cellStyle, HSSFCellStyle cellStyle2) {
        HSSFRow row;// 将第一行的三个单元格给合并,模板固定
        //注意 java的参数是从0开始 即表示excel中的一行或者第一列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));
        row = sheet.createRow(0);
        HSSFCell beginCell0 = row.createCell(0);
        beginCell0.setCellValue("授课人信息表");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell0.setCellStyle(cellStyle);

        //第二行的单元格进行合并,语句提示
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 8));
        row = sheet.createRow(1);
        HSSFCell beginCell1 = row.createCell(0);
        beginCell1.setCellValue("请按照模板字段和单元格格式提交数据");
        //cellStyle为水平居中字体加粗单元格样式
        beginCell1.setCellStyle(cellStyle);

        HSSFRow headRow = sheet.createRow(2);
        headRow.createCell(0).setCellValue("*姓名");
        headRow.createCell(1).setCellValue("*电话");
        headRow.createCell(2).setCellValue("QQ");
        headRow.createCell(3).setCellValue("微信");
        headRow.createCell(4).setCellValue("邮箱");
        headRow.createCell(5).setCellValue("擅长内容");
        headRow.createCell(6).setCellValue("课酬");
        headRow.createCell(7).setCellValue("常驻地");
        headRow.createCell(8).setCellValue("备注");
        headRow.setHeightInPoints(25); //设置行的高度
        for (int i = 0; i < 9; i++) {
            headRow.getCell(i).setCellStyle(cellStyle2);
        }
        //设置所有列列宽
        for (int i = 0; i < 9; i++) {
            sheet.setColumnWidth(i, 20 * 256);
        } // 设置列的宽度
        return sheet;
    }
    //导入excel
    @RequestMapping("/import")
    public String importExcel(@RequestParam("file") MultipartFile file, Model model, HttpSession session) {
        //固定格式  参数file 为 文件上传的input的name
        try {
            InputStream inputStream = null;
            inputStream = file.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());

            HSSFSheet sheet = workbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();
            Teacher t = null;
            HSSFRow row = null;

            //从第四行开始读取数据
            List<Teacher> list = new ArrayList<>();
            for (int i = 3; i <= lastRowNum; i++) {
                t = new Teacher();
                row = sheet.getRow(i);
                if(StringUtils.isEmpty(row.getCell(0).getStringCellValue())&&StringUtils.isEmpty(row.getCell(1).getStringCellValue())){
                    break;//如果姓名和电话为空则判断以下是空行无数据，停止写入
                }
                //第一列
                t.setTName(row.getCell(0).getStringCellValue());
                //第二列
                t.setTPhone(row.getCell(1).getStringCellValue());
                //第三列
                t.setTQq(row.getCell(2).getStringCellValue());
                //第四列
                t.setTWechat(row.getCell(3).getStringCellValue());
                //第五列
                t.setTEmail(row.getCell(4).getStringCellValue());
                //第六列
                t.setTMajor(row.getCell(5).getStringCellValue());
                //第七列
                t.setTMoney(row.getCell(6).getNumericCellValue());
                //第八列
                t.setTAddress(row.getCell(7).getStringCellValue());
                //第九列
                t.setTRemarks(row.getCell(8).getStringCellValue());
                //添加一个对象,循环,直到结束
                list.add(t);
            }
            if (teacherService.addTeacherList(list)){
                MessageUtil.returnInfoPage("2","/teacher/list","导入成功",model);
                return "message";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        MessageUtil.returnInfoPage("3", "/teacher/list", "导入失败！请检查", model);
        return "message";
    }

}
